package com.example.test0520;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.test0520.activity.AddActivity;
import com.example.test0520.activity.BaseActivity;
import com.example.test0520.activity.SetActivity;
import com.example.test0520.adapter.ViewPageAdapter;
import com.example.test0520.api.TtitCallback;
import com.example.test0520.databinding.ActivityMainBinding;
import com.example.test0520.fragment.WeatherFragment;
import com.example.test0520.util.City;
import com.example.test0520.util.CityData;
import com.example.test0520.util.CityList;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class MainActivity extends AppCompatActivity {
    public static final int WEEKDAYS = 7;
    public static String[] WEEK = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THRUSDAY", "FRIDAY", "SATURDAY"};

    private List<CityData.ResultBean> cityData;

    //申请定位权限
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 200) {//刚才的识别码
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//用户同意权限,执行我们的操作
                setPosit();//开始定位
            } else {//用户拒绝之后,当然我们也可以弹出一个窗口,直接跳转到系统设置页面
                Toast.makeText(MainActivity.this, "未开启定位权限,请手动到设置去开启权限", Toast.LENGTH_LONG).show();
            }
        }

    }


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    private ActivityMainBinding binding;
    private MyAMapLocationListener listener;
    public AMapLocationClientOption mLocationOption = null;
    private String city;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {//未开启定位权限
            //开启定位权限,200是标识码
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 200);
        } else {
            //setPosit();//开始定位
            Toast.makeText(MainActivity.this, "已开启定位权限", Toast.LENGTH_LONG).show();
        }
        listener = new MyAMapLocationListener();

        setPosit();
        setListener();
    }

    public void sc(int pos) {
        Log.d("TAG", "sc: " + pos);
        binding.viewpage2.setCurrentItem(pos + 1, false);
    }
//
//    @Override
//    protected void onStart() {
//        super.onStart();
//    }

    private void setListener() {
        binding.addImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, AddActivity.class));
            }
        });
        binding.setImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, SetActivity.class));
            }
        });
    }

    //网络请求
    private void getInfo() {
        List<CityList> cityListData = LitePal.findAll(CityList.class);
        String TAG = "MainActivity";
        Log.d(TAG, "getInfo: c" + cityListData.size());
        //将全国省市数据存入数据库
        if (cityListData.size() == 0) {
            String key = "827a80d1658ed0b9055b479f77824e86";
            network("http://apis.juhe.cn/simpleWeather/")
                    .getCityInfo(key)
                    .enqueue(new Callback<CityData>() {
                        @Override
                        public void onResponse(Call<CityData> call, Response<CityData> response) {
                            cityData = response.body().getResult();
                            for (CityData.ResultBean bean :
                                    cityData) {
                                new CityList(bean.getProvince(), bean.getCity(), bean.getDistrict()).save();
                            }


                        }

                        @Override
                        public void onFailure(Call<CityData> call, Throwable t) {

                        }
                    });
        }
        setRender();
    }

    //渲染数据
    private void setRender() {
        List<City> all = LitePal.findAll(City.class);
        ArrayList<Fragment> fragmentList = new ArrayList<>();
        WeatherFragment fragment = WeatherFragment.newInstance(city, binding.viewpage2);
        fragmentList.add(fragment);
        for (City c :
                all) {
            if (c.getCity().equals(c.getDistrict())) {
                WeatherFragment f = WeatherFragment.newInstance(c.getCity(), binding.viewpage2);
                fragmentList.add(f);
            } else {
                WeatherFragment f = WeatherFragment.newInstance(c.getDistrict(), binding.viewpage2);
                fragmentList.add(f);
            }

        }
        binding.viewpage2.setAdapter(new ViewPageAdapter(this, fragmentList));
        Intent intent = getIntent();
        int pos = intent.getIntExtra("pos", -1);
        Log.d("TAG", "setRender: pos" + pos);
        if (pos != -1) {
            sc(pos);
        }

    }

    public static String DateToWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayIndex = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayIndex < 1 || dayIndex > WEEKDAYS) {
            return null;
        }

        return WEEK[dayIndex - 1];
    }

    //使用sdk定位
    private void setPosit() {
//初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
//设置定位回调监听
        mLocationClient.setLocationListener(listener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(false);

        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        //mLocationOption.setOnceLocationLatest(true);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);

        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
//启动定位
        mLocationClient.startLocation();
        //声明定位回调监听器

    }

    private class MyAMapLocationListener implements AMapLocationListener {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            showToast("进来了？");
            Log.d("TAG", "外层: " + aMapLocation.getCity());
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    Log.d("TAG", "onLocationChanged: " + "城市：" + aMapLocation.getCity() + "国家" + aMapLocation.getCountry() + "省份" + aMapLocation.getProvince());

                    city = aMapLocation.getCity();
                    int c = city.indexOf("市");
                    city = removeCharAt(city, c);
                    getInfo();
                } else {
                    Log.e("TAG", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。

                }
            }

        }

        public String removeCharAt(String s, int pos) {
            return s.substring(0, pos) + s.substring(pos + 1);
        }
    }

    public TtitCallback network(String url) {
        TtitCallback ttitCallback = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(TtitCallback.class);
        return ttitCallback;
    }

    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}